<template>
  <div>
    <el-form ref="myform1" :model="formItem" :rules="rules" label-width="120px" size="mini">
      <el-row>
        <el-col :span="12">
          <el-form-item label="工单标题" prop="title">
            <el-input v-model="formItem.title" placeholder="请输入标题" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="到货日期" prop="receiveDate">
            <el-date-picker v-model="formItem.receiveDate" type="date" placeholder="请选择到货日期" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入库类型" prop="categories">
            <el-radio-group v-model="formItem.categories" size="mini" @change="categorieChange">
              <el-radio label="1" value="1">非消耗品</el-radio>
              <!-- <el-radio label="2" value="2" border>低值易耗品</el-radio> -->
              <el-radio label="3" value="3">消耗品</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入库合同" prop="contractName">
            <el-input v-model="formItem.contractName" placeholder="请选择合同" @focus="handleContractClick" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="购置日期" prop="purchaseDate">
            <el-date-picker v-model="formItem.purchaseDate" type="date" placeholder="请选择购置日期" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="存放位置" prop="location">
            <treeselect
              v-model="formItem.location"
              :multiple="false"
              :options="myStorehouses"
              :disable-branch-nodes="true"
              placeholder="请选择存放位置"
              @input="inputLocation"
              @select="selectLocation"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="综合管理部" prop="comprehensive">
            <el-radio-group v-model="formItem.comprehensive">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注信息" prop="remark">
            <el-input v-model="formItem.remark" type="textarea" placeholder="请输入备注信息" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="合同明细">
            <div v-show="step === '1'">
              <PageableTable
                class="fixed-table-table"
                :columns="insideColumns"
                :loading="false"
                :table-height="240"
                :data="formItem.contractProductList"
                :disable-pageable="true"
              >
                <el-table-column label="序号" type="index" width="50" />
                <el-table-column v-for="column in insideColumns" :key="column.key" :label="column.title" :prop="column.key" :width="column.width" :sortable="column.sortable">
                  <template slot-scope="scope">
                    <column-render :render="column.render" :row="scope.row" :column="column" />
                  </template>
                </el-table-column>
                <el-table-column label="本次入库数量">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.count" size="mini" :min="0" :precision="0" :step="1" :max="scope.row.maxCount" />
                  </template>
                </el-table-column>
              </PageableTable>
            </div>
            <div v-show="step === '2'" class="ruku-kj-form">
              <PageableTable
                :columns="assetColumns"
                :loading="false"
                :table-height="240"
                :data="formItem.assetList"
                :disable-pageable="true"
                class="fixed-table-table"
              >
                <el-table-column v-for="column in assetColumns" :key="column.key" :width="column.width" :label="column.title" :prop="column.key" :sortable="column.sortable">
                  <template slot-scope="scope">
                    <column-render :render="column.render" :row="scope.row" :column="column" />
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
                  <template slot-scope="{row}">
                    <el-button v-if="row.edit === false && !row.peijian " type="text" size="mini" icon="el-icon-edit-outline" title="编辑" @click="row.edit = true" />
                    <el-button v-if="row.edit === true && !row.peijian " type="text" size="mini" icon="el-icon-close" title="取消" @click="cancelEdit(row)" />
                  </template>
                </el-table-column>
              </PageableTable>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row>
      <el-col :offset="20" :span="4">
        <div style="display:block;margin-top:10px;text-align:right">
          <el-button size="mini" @click="btnCancel">取 消</el-button>
          <el-button v-if="step==='1' && formItem.categories !== '3'" :disabled="formItem.contractProductList.length <= 0" size="mini" @click="changeStep('2')">下一步</el-button>
          <el-button v-if="step==='2' && formItem.categories !== '3'" size="mini" @click="changeStep('1')">上一步</el-button>
          <el-button v-if="(step==='2' && formItem.categories !== '3') || formItem.categories === '3'" size="mini" type="primary" @click="commit">提 交</el-button>
        </div>
      </el-col>
    </el-row>
    <SelectDialog v-if="contractFormVisible" title="选择合同" :append-to-body="true" :show="contractFormVisible" @on-ok="selectContractOk" @on-cancel="selectContractCancel">
      <contract
        ref="contract"
        :for-selection="true"
        belongs="kj"
        :multiple-selected="false"
        :whether-arrival="false"
        :types="types"
      />
    </SelectDialog>
  </div>
</template>
<script>
import treeselect from '@neu/biz-core/components/TreeSelect'
import { create, detail } from '@neu/dcam-ui/api/arrival'
import PageableTable from '@neu/biz-core/components/PageableTable'
import SelectDialog from '@neu/biz-core/components/SelectDialog'
import contract from '@neu/dcam-ui/views/contract'
import { formatDate } from '@neu/biz-core/utils/utils'
import { list as contractItemList } from '@neu/dcam-ui/api/contractItem'
import { tree as locationTree } from '@neu/dcam-ui/api/location'
import { list as getAllStorehouse } from '@neu/dcam-ui/api/storehouse'

const insideColumns = [
  { title: '资产分类', width: 120, key: 'typeName' },
  { title: '产品名称', width: 120, key: 'productName' },
  { title: '规格型号', width: 120, key: 'specification' },
  { title: '单价（元）', width: 100, key: 'amount' },
  { title: '合同数量', width: 100, key: 'sourceCount' },
  { title: '已入库数量', width: 100, key: 'acceptedCount' }
]
const formItem = {
  workOrderNum: '',
  taskId: '',
  title: '',
  receiveDate: null,
  contractCode: '',
  contractName: '',
  remark: '',
  annex: [],
  type: 'dcamArrival',
  status: 'temporary',
  purchaseDate: null,
  contractProductList: [],
  comprehensive: true,
  categories: '1',
  assetList: []
}
export default {
  components: {
    PageableTable,
    SelectDialog,
    contract,
    treeselect
  },
  props: {
    taskId: {
      required: false,
      type: String,
      default: 'NULL'
    },
    workOrderNum: {
      required: false,
      type: String,
      default: ''
    }
  },
  data() {
    return {
      step: '1',
      newAsset: [],
      types: '',
      availableLocations: [],
      flattenTreeData: [],
      formItem: {
        ...formItem
      },
      /** 是否显示合同信息 */
      contractFormVisible: false,
      // 表单验证规则
      rules: {
        title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        receiveDate: [{ required: true, message: '验收日期不能为空', trigger: 'blur' }],
        categories: [{ required: true, message: '请选择入库类型', trigger: 'blur' }],
        contractCode: [{ required: true, message: '合同不能为空', trigger: 'change' }],
        purchaseDate: [{ required: true, message: '购置日期不能为空', trigger: 'blur' }],
        location: [{ required: true, message: '存放位置不能为空', trigger: 'blur' }],
        remark: [
          { max: 500, message: '长度不能超过500', trigger: 'blur' }
        ]
      },
      // 表格列
      insideColumns: [...insideColumns],
      /** 所有仓库 */
      storehouses: [],
      // 资产列定义
      assetColumns: [
        { title: '类型名称', width: 100, key: 'typeName' },
        { title: '规格型号', key: 'specification' },
        { title: '计量单位', key: 'measureUnit' },
        { title: '品牌', key: 'brand' },
        { title: '序列号', width: 100, key: 'serialnumber',
          render: (h, params) => {
            return params.row.edit ? (
              <el-input size='mini' v-model={params.row.serialnumber} placeholder='序列号' />
            ) : h('span', params.row.serialnumber)
          }
        },
        { title: '位置', width: 160, key: 'locationName', render: (h, params) => {
          return params.row.edit ? (
            <treeselect v-model={params.row.location} multiple={false} options={this.availableLocations} placeholder='位置'/>
          ) : h('span', params.row.locationName)
        } },
        { title: '使用期限', width: 80, key: 'usePeriod',
          render: (h, params) => {
            return params.row.edit ? (
              <el-input size='mini' v-model={params.row.usePeriod} placeholder='' />
            ) : h('span', params.row.usePeriod)
          } },
        { title: '维保开始', width: 148, key: 'maintenanceStartTime',
          render: (h, params) => {
            return params.row.edit ? (
              <el-date-picker size='mini' v-model={params.row.maintenanceStartTime} type='date' align='right' />
            ) : h('span', formatDate(params.row.maintenanceStartTime, 'YYYY-MM-DD'))
          } },
        { title: '维保结束', width: 148, key: 'maintenanceEndTime',

          render: (h, params) => {
            return params.row.edit ? (
              <el-date-picker size='mini' v-model={params.row.maintenanceEndTime} type='date' align='right' />
            ) : h('span', formatDate(params.row.maintenanceEndTime, 'YYYY-MM-DD'))
          } }
      ]
    }
  },
  computed: {
    myStorehouses: function() {
      const flatTree = this.flattenTreeDataClosure(this.availableLocations)
      return this.storehouses.filter(it => !!flatTree.find(n => n.code === it.locationCode)).map(it => {
        return {
          code: it.locationCode,
          title: it.locationName
        }
      })
    }
  },
  created() {
    this.fetch()
    this.formItem.receiveDate = new Date()
    locationTree('kj').then(response => {
      this.availableLocations = response.data
      this.flattenTreeData = this.flattenTreeDataClosure(this.availableLocations)
    })
    getAllStorehouse().then(response => {
      this.storehouses = response.data
    })
  },
  methods: {
    // 获取借用工单信息
    fetch() {
      if (this.workOrderNum !== 'NULL') {
        detail(this.workOrderNum, this.taskId).then(response => {
          this.formItem = { ...response.data }
          // 查询合同项详情
          contractItemList({ 's_code': this.formItem.contractCode }).then(res => {
            const contractProductList = res.data.filter(m => m.acceptedCount !== m.count)
            if (res.data.length === 0) {
              // 不判断
            } else {
              this.newAsset = []

              if (this.formItem.categories !== '3') {
                // 生成模板信息
                var i = 0
                this.newAsset = contractProductList.map(l => {
                  return {
                    key: i++,
                    /** 资产分类名 */
                    typeName: l.assetTypeName,
                    /** 资产分类编码 */
                    typeCode: l.assetTypeCode,
                    /** 产品名 */
                    productName: l.productName,
                    /** 规格型号 */
                    specification: l.standard,
                    /** 数量 */
                    count: 1,
                    /** 单个资产价格 */
                    money: l.amount,
                    locationName: '',
                    location: null,
                    usePeriod: '',
                    maintenanceStartTime: null,
                    maintenanceEndTime: null,
                    /** 合同项ID */
                    itemId: l.id,
                    edit: false,
                    peijian: l.type === '2',
                    brand: l.brand,
                    measureUnit: l.measureUnit
                  }
                })
              }
              this.contractFormVisible = false
            }
          })
        })
      } else {
        this.formItem = {
          ...formItem
        }
      }
    },
    handleContractClick() {
      this.types = this.formItem.categories === '1' ? 'purchase,sporadic' : (this.formItem.categories === '2' ? 'purchase,sporadic' : 'xh')
      this.contractFormVisible = true
    },
    selectContractCancel() {
      this.contractFormVisible = false
    },
    commit() {
      this.$refs.myform1.validate((valid) => {
        if (valid) {
          if (this.formItem.assetList.length === 0 && this.formItem.categories !== '3') {
            return this.$message({
              showClose: true,
              message: '没有可入库的资产',
              type: 'error'
            })
          } else if (this.formItem.categories === '3' && this.formItem.contractProductList.reduce(function(total, currentValue) {
            return total + currentValue.count
          }, 0) === 0) {
            return this.$message({
              showClose: true,
              message: '没有可入库的资产',
              type: 'error'
            })
          }
          const data = { ...this.formItem }
          data.workOrderNum = this.workOrderNum
          data.taskId = this.taskId
          // 时间
          data.receiveDate = new Date(this.formItem.receiveDate).getTime()
          data.purchaseDate = new Date(this.formItem.purchaseDate).getTime()
          // data.categories = this.categories
          data.assetList.forEach(l => {
            if (l.maintenanceStartTime) {
              l.maintenanceStartTime = new Date(l.maintenanceStartTime).getTime()
            }
            if (l.maintenanceEndTime) {
              l.maintenanceEndTime = new Date(l.maintenanceEndTime).getTime()
            }

            // 位置
            const location = this.flattenTreeData.find(s => s.code === l.location)
            l.locationName = location ? location.title : ''
          })
          create(data).then(res => {
            if (res.status === 'success') {
              this.$emit('cancelNewOrderForm', 'refresh')
            }
          })
        }
      })
    },
    selectContractOk() {
      var selectContract = this.$refs.contract.selections

      if (selectContract.length > 1) {
        return this.$message({
          showClose: true,
          message: '只能选择一个合同',
          type: 'error'
        })
      } else if (selectContract.length === 1) {
        // 查询合同项详情
        contractItemList({ 's_contractId': selectContract[0].id }).then(res => {
          // 过滤掉已经全部完成入库的合同项
          const contractProductList = res.data.filter(m => m.acceptedCount !== m.count)
          if (res.data.length === 0) {
            return this.$message({
              showClose: true,
              message: selectContract[0].name + '没有可入库的资产',
              type: 'error'
            })
          } else {
            this.formItem.contractCode = selectContract[0].code
            this.formItem.contractName = selectContract[0].name
            this.newAsset = []

            if (this.formItem.categories !== '3') {
              // 生成模板信息
              let i = 0
              this.newAsset = contractProductList.map(l => {
                return {
                  key: i++,
                  /** 资产分类名 */
                  typeName: l.assetTypeName,
                  /** 资产分类编码 */
                  typeCode: l.assetTypeCode,
                  /** 产品名 */
                  productName: l.productName,
                  /** 规格型号 */
                  specification: l.standard,
                  /** 数量 */
                  count: 1,
                  /** 单个资产价格 */
                  money: l.amount,
                  locationName: '',
                  location: null,
                  usePeriod: '',
                  maintenanceStartTime: null,
                  maintenanceEndTime: null,
                  /** 合同项ID */
                  itemId: l.id,
                  edit: false,
                  peijian: l.type === '2',
                  brand: l.brand,
                  measureUnit: l.measureUnit
                }
              })
            }

            this.formItem.contractProductList = contractProductList.map(l => {
              return {
                /** 资产分类名 */
                typeName: l.assetTypeName,
                /** 资产分类编码 */
                typeCode: l.assetTypeCode,
                /** 产品名 */
                productName: l.productName,
                /** 规格型号 */
                specification: l.standard,
                /** 原值 */
                money: null,
                /** 数量 */
                count: 1,
                maxCount: l.count - l.acceptedCount,
                /** */
                acceptedCount: l.acceptedCount,
                sourceCount: l.count,
                /** 单个资产价格 */
                amount: l.amount,
                /** 合同项描述 */
                description: l.description,
                itemId: l.id,
                peijian: l.type === '2',
                brand: l.brand,
                measureUnit: l.measureUnit
              }
            })

            this.contractFormVisible = false
          }
        })
      } else if (selectContract.length < 1) {
        this.formItem.contractCode = ''
        this.formItem.contractName = ''
        this.contractFormVisible = false
        this.formItem.contractProductList = []
      }
    },
    btnCancel() {
      this.$emit('cancelNewOrderForm', 'refresh')
    },
    // 位置选择
    selectLocation(obj) {
      this.formItem.locationName = obj.title || ''
    },
    // 位置选择
    inputLocation(value) {
      if (!value) {
        this.formItem.locationName = value || ''
      }
    },
    categorieChange(value) {
      this.step = '1'
      this.formItem.contractProductList = []
      this.formItem.assetList = []
      this.newAsset = []
      this.formItem.contractCode = ''
      this.formItem.contractName = ''
    },
    changeStep(value) {
      this.step = value
      if (value === '2') {
        // 修改状态
        this.formItem.assetList = []

        // 如果是空的生成资产信息
        for (let index = 0; index < this.formItem.contractProductList.length; index++) {
          const productItem = this.formItem.contractProductList[index]

          // 过滤生成的资产的信息
          const filterList = this.formItem.assetList.filter(l => l.key === index)
          for (let ind = 0; ind < productItem.count - filterList.length; ind++) {
            this.formItem.assetList.push(JSON.parse(JSON.stringify(this.newAsset[index])))
          }
        }
      }
    },
    cancelEdit(row) {
      row.edit = false
      // row.location = 'ANNJDS'
      if (row.location) {
        // 位置
        const location = this.flattenTreeData.find(s => s.code === row.location)
        row.locationName = location ? location.title : ''
      } else {
        row.locationName = ''
      }
    },
    // 扁平化树形结构
    flattenTreeDataClosure(data) {
      const treeData = data
      const flattenData = []
      function flattenTree(data, parentKey) {
        data.forEach(ele => {
          const { title, code, children } = ele
          flattenData.push({ title, code, parentKey })
          if (children) {
            flattenTree(children, code)
          }
        })
      }
      flattenTree(treeData, null)
      return flattenData
    }
  }
}
</script>
<style>
  .el-table th.gutter{
    display: table-cell !important;
  }
</style>
